<template>
	<view style="border: 1px solid #ccc">
		<Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
			:mode="mode" />
		<Editor style="height: 500px; overflow-y: hidden;" v-model="valueHtml" @onBlur="handleBlur"
			:defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" @customPaste="customPaste" />
	</view>
</template>

<script setup>
	import '@wangeditor/editor/dist/css/style.css' // 引入 css

	import { onBeforeUnmount, ref, shallowRef, reactive, onMounted, defineEmits } from 'vue'
	import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
	const editorRef = shallowRef()
	const emit = defineEmits(['onclick'])
	const mode = ref('default')
	let arr = reactive([])
	let pic = reactive([])
	// 内容 HTML
	const valueHtml = ref('<p>hello</p>')
	const toolbarConfig = {}
	const editorConfig = { placeholder: '请输入内容...', MENU_CONF: {} }
	editorConfig.MENU_CONF['uploadImage'] = {
		// 上传图片的配置
		customBrowseAndUpload(insertFn) {
			uni.chooseImage({
				success(e) {
					arr.push(...e.tempFiles)
					// console.log(arr);
					let newarr = arr.map(async item => {
						return await uniCloud.uploadFile({
							cloudPath: item.name,
							filePath: item.path
						})
					})
					// console.log(newarr);
					Promise.all(newarr).then(res => {
						console.log(res);
						pic.push(...res)
						pic.forEach(item => {
							insertFn(item.fileID)
						})
					})
				}
			})

		}

	}

	// 组件销毁时，也及时销毁编辑器
	onBeforeUnmount(() => {
		const editor = editorRef.value
		if (editor == null) return
		editor.destroy()
	})

	const handleCreated = (editor) => {
		editorRef.value = editor // 记录 editor 实例，重要！
	}

	const customPaste = (editor, event, callback) => {
		// console.log('ClipboardEvent 粘贴事件对象', html)
		const html = event.clipboardData.getData('text/html') // 获取粘贴的 html
		const text = event.clipboardData.getData('text/plain') // 获取粘贴的纯文本
		valueHtml.value = text
		// const rtf = event.clipboardData.getData('text/rtf') // 获取 rtf 数据（如从 word wsp 复制粘贴）

		// 自定义插入内容
		// editor.insertText(html, text)

		// 返回 false ，阻止默认粘贴行为
		event.preventDefault()
		callback(false) // 返回值（注意，vue 事件的返回值，不能用 return）

		// 返回 true ，继续默认的粘贴行为
		// callback(true)
	}
	const handleBlur = (editor) => {
		console.log('blur', valueHtml)
		emit('onclick', valueHtml)
	}
</script>